package chat.server;

import chat.Consts;
import chat.LogManager;
import chat.server.model.DbHelper;
import chat.server.model.User;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server {

    private int port = 8081;
    private ServerSocket serverSocket;
    private ExecutorService executorService;
    private final int POOL_SIZE = 10;
    private HashMap<String, Socket> connectedClients;

    public Server() throws IOException {
        serverSocket = new ServerSocket(port);
        executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE);
        System.out.println("服务器启动");
        connectedClients = new HashMap<String, Socket>();
    }

    public void service() {
        while (true) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                executorService.execute(new Handler(socket, connectedClients));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new Server().service();
    }
}

class Handler implements Runnable {

    private String mUid;
    private Socket socket;
    private HashMap<String, Socket> connectedClients;

    public Handler(Socket socket, HashMap<String, Socket> connectedClients) {
        this.socket = socket;
        this.connectedClients = connectedClients;
    }

    private DataOutputStream getWriter(Socket socket) throws IOException {
        OutputStream s = socket.getOutputStream();
        return new DataOutputStream(s);
    }

    private DataInputStream getReader(Socket socket) throws IOException {
        InputStream in = socket.getInputStream();
        return new DataInputStream(in);
    }

    public void echo(String msg) {
        System.out.print("echo:" + msg);
    }

    public void echo(int msg) {
        System.out.print("echo:" + String.valueOf(msg));
    }

    public void run() {
        try {
            System.out.println("New connection accepted " + socket.getInetAddress() + ":" + socket.getPort());
            DataInputStream reader = getReader(socket);
            DataOutputStream writer = getWriter(socket);
            int msg = -1;
            while ((msg = reader.read()) != -1) {
                echo(msg);
                switch (msg) {
                    case Consts.LOGIN: {
                        String username = reader.readUTF();
                        String password = reader.readUTF();
                        String ip = reader.readUTF();
                        System.out.println(String.format("%s, %s, %s", username, password, ip));
                        DbHelper.getInstance().updateIPByUid(ip, username);
                        DbHelper.getInstance().updateOnline(username, true);
                        User user = null;
                        try {
                            user = DbHelper.getInstance().getUserByUid(username);
                        } catch (SQLException ex) {
                            LogManager.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        // 加入Map
                        mUid = username;
                        connectedClients.put(username, socket);

                        if (user != null) {
                            writer.write(Consts.LOGIN_SUCCESS);
                            writer.writeUTF(user.nick);
                            Vector<User> friends = new Vector<User>();
                            friends = DbHelper.getInstance().getFriendsByUid(username);
                            StringBuilder sb = new StringBuilder();
                            for (User u : friends) {
                                sb.append(u.nick + "#" + u.uid + "#" + Boolean.toString(u.online));
                                sb.append("\t");
                            }
                            writer.writeUTF(sb.toString());

                            for (User u : friends) {
                                // 上线通知在线好友
                                if (u.online) {
                                    Socket sock = connectedClients.get(u.uid);
                                    if (sock != null) {
                                        DataOutputStream wr = getWriter(sock);
                                        wr.write(Consts.ME_ONLINE);
                                        wr.writeUTF(username);
                                    }
                                }
                            }
                        } else {
                            writer.write(Consts.LOGIN_FAILED);
                        }
                        break;
                    }
                    case Consts.GET_IP: {
                        String uid = reader.readUTF();
                        echo(uid);
                        String uip = DbHelper.getInstance().getIPByUid(uid);
                        if (uip != null) {
                            writer.write(Consts.GET_IP_SUCCESS);
                            writer.writeUTF(uip);
                        }
                        break;
                    }
                    case Consts.REGISTER: {
                        String uid = reader.readUTF();
                        String password = reader.readUTF();
                        String nick = reader.readUTF();
                        User user = DbHelper.getInstance().register(uid, password, nick);
                        if (user != null) {
                            writer.write(Consts.REGISTER_SUCCESS);
                        }
                        break;
                    }
                    case Consts.ADD_FRIEND: {
                        String uid1 = reader.readUTF();
                        String uid2 = reader.readUTF();
                        boolean success = DbHelper.getInstance().addFriend(uid1, uid2);
                        echo(Consts.ADD_FRIEND_SUCCESS);
                        writer.write(Consts.ADD_FRIEND_SUCCESS);

                        if (DbHelper.getInstance().getUserOnline(uid2)) {
                            Socket sock = connectedClients.get(uid2);
                            if (sock != null) {
                                DataOutputStream w = getWriter(sock);
                                w.write(Consts.FRIEND_REQUEST);
                                w.writeUTF(uid1);
                            }
                        }
                        break;
                    }
                    case Consts.ADD_FRIEND_COMPLETE: {
                        String uid1 = reader.readUTF();
                        String uid2 = reader.readUTF();
                        boolean success = DbHelper.getInstance().addFriend(uid1, uid2);
                        writer.write(Consts.ADD_FRIEND_COMPLETE_SUCCESS);
                        break;
                    }
                    case Consts.GET_ALL_USER_NOT_FRIENDS: {
                        String uid = reader.readUTF();
                        Vector<User> users = new Vector<User>();
                        echo(uid);
                        users = DbHelper.getInstance().getAllUserNotFriends(uid, false);
                        StringBuilder sb = new StringBuilder();
                        for (User u : users) {
                            sb.append(u.nick + "#" + u.uid + "#" + Boolean.toString(u.online));
                            sb.append("\t");
                        }
                        writer.write(Consts.GET_ALL_USER_NOT_FRIENDS_SUCCESS);
                        writer.writeUTF(sb.toString());
                        break;
                    }
                    case Consts.CHANGE_NICK: {
                        String uid = reader.readUTF();
                        String nick = reader.readUTF();
                        DbHelper.getInstance().changeProfile(uid, nick);
                        break;
                    }
                    case Consts.CHANGE_PASSWORD: {
                        String uid = reader.readUTF();
                        String password = reader.readUTF();
                        DbHelper.getInstance().changePassword(uid, password);
                        break;
                    }
                    default:
                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            echo(mUid + "离线");
            DbHelper.getInstance().updateOnline(mUid, false);
            Vector<User> friends = DbHelper.getInstance().getFriendsByUid(mUid);
            for (User u : friends) {
                // 离通知在线好友
                if (u.online) {
                    Socket sock = connectedClients.get(u.uid);
                    if (sock != null) {
                        DataOutputStream wr = null;
                        try {
                            wr = getWriter(sock);
                            wr.write(Consts.ME_OFFLINE);
                            wr.writeUTF(mUid);
                        } catch (IOException ex) {
                            Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
                        } finally {
                            try {
                                wr.close();
                            } catch (IOException ex) {
                                Logger.getLogger(Handler.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                }
            }
            try {
                if (socket != null) {
                    socket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
